// pages/activity/evaluationAnswer/index.js
const api = require("../../../config/api")
const request = require("../../../utils/request")
const { setStorage, getStorage, getBarAndTitleHeight } = require("../../../utils/util")
let app = getApp()
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		questionNumber: 0,
    answerList: [],
    questionList: [], // 题目列表
    currentQuestion: {},
    currentOptionCode: '',
    answerOptionList: [],
    maxLength: 0, // 题目数量
		isCurrentStorage: 0, // 对应当前用户、孩子档案、答题记录缓存
		evaluationUserId: '', // 缓存答题用户id
		evaluationPatientId: '',// 缓存答题孩子档案id
		evaluationAnswerList: [], // 缓存答题答案数组
		evaluationIsChild: '',// 缓存答案是孩子还是家长
		patientId: '',// 当前孩子档案id
		userId: '',// 当前用户id
		crowd: 1,// 所属人群
		firstQuestion: {
			id: 0,
      subject: "孩子目前处于什么学龄段",
      executiveSkill: 12,
      crowd: 6,
      optionList: [
        {
          name: "入学前/幼儿园",
          fraction: 1
        },
        {
          name: "1-3年级",
          fraction: 2
        },
        {
          name: "4-5年级",
          fraction: 3
        },
        {
          name: "6-8年级",
          fraction: 4
        }
      ]
		},
		isChild: 1, // 是孩子还是家长 1-孩子 2-家长
    isCurrentStorage: 0, // 是当前孩子缓存
    warnShow: false,// 提醒弹窗是否显示
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
    // app.removeQuestionStorage()

		const patientId = wx.getStorageSync('patientInfo')?.id
		const userId = wx.getStorageSync('userId')
		let evaluationUserId = getStorage("evaluationUserId")
		let evaluationPatientId = getStorage("evaluationPatientId")
		let evaluationAnswerList = getStorage("evaluationAnswerList")
    let evaluationIsChild = getStorage("evaluationIsChild")

    
    let { firstQuestion } = this.data
		let isCurrentStorage = 0 
		let	crowd = 1
    let isChild = Number(options?.isChild) || 1

    let questionArr = [ firstQuestion ]
		this.setData({
			patientId,
			userId,
			evaluationUserId,
			evaluationPatientId,
			evaluationAnswerList,
      questionList: questionArr,
      // currentQuestion: questionArr[0],
      currentOptionCode: '',
      questionNumber: 0,
      isChild,
      ...getBarAndTitleHeight(),
		})
    
    // 判断是否有缓存
		// 是家长答题
    if( evaluationAnswerList.length>0 && userId === evaluationUserId && patientId === evaluationPatientId && isChild === evaluationIsChild){
      isCurrentStorage = 1 // 是当前缓存
      if(isChild === 1){
        crowd = evaluationAnswerList[0].optionScore // 所属年龄段--第一题答案
      }else{
        crowd = 5 // 所属年龄段--家长
      }
      this.setData({
        crowd,
        isCurrentStorage,
      })
      this.getQuestionList(0)
		}else{
      if(isChild === 2){
        crowd = 5
        this.setData({
          crowd
        })
        this.getQuestionList(0)
      }else{
        this.setData({
          currentQuestion: questionArr[0],
        })
      }
    }
	},
	// 题目列表
	getQuestionList: async function (key) {
    let { isCurrentStorage, evaluationAnswerList, crowd, isChild, firstQuestion } = this.data
    
		const res = await request.get(api.getQuestionChildList, {
			crowd
    },{loading: false})
    
    console.log('请求题目列表--res----------------',res)
		if (res.httpStatus === 200) {
			res.data.map((it) => {
				it.optionList?.map((item) => {
					item.checked = false
					item.selectId = ''
				})
      })
      
      let list = isChild=== 1 ?  [firstQuestion, ...res.data] : res.data
			this.setData({
				questionList: list,
				maxLength: list.length,
      })
      if(key === 0){
        if (res.data.length > 0) {
          if(isCurrentStorage === 1){
            let answerLength = evaluationAnswerList.length
            this.setData({
              answerOptionList: evaluationAnswerList,
              currentQuestion: list[answerLength],
              currentOptionCode: '',
              questionNumber: answerLength,
            })
          }else{
            this.setData({
              currentQuestion: list[0],
            })
          }
        }
      }else if(key===2){
        setTimeout(()=>{
          this.handleNext()
        },150)
      }
		}else{
      // wx.showToast({
      //   title: '您的网络异常，请稍后再试',
      //   icon: 'none'
      // })
    }
	},
	// 单选
  selectOne: function (e) {
    let { fraction, item, index } = e.currentTarget.dataset
    let { currentQuestion, isChild, questionNumber } = this.data

    console.log('selectOne----currentQuestion----',currentQuestion)

		currentQuestion?.optionList?.map((it) => {
			if (it.fraction === item.fraction) {
				it.checked = true
			} else {
				it.checked = false
			}
		})
    this.setData({
      currentOptionCode: fraction,
      currentQuestion: currentQuestion,
    })
    if(questionNumber === 0 && isChild === 1){
      this.setData({
        crowd: index + 1,
        answerOptionList: [],
        isCurrentStorage: 0
      })
      this.getQuestionList(2)
      
    }else{
      setTimeout(()=>{
        this.handleNext()
      },150)
    }
  },
  // 将最后一个对象截掉
  truncate(arr) {
    return arr.filter(function(ele,idx,arr){
        return arr.length - 1 !== idx;
    });
  },
  // 将第一个对象截掉
  up(arr) {
    return arr.filter(function(ele,idx,arr){
        return idx !== 0;
    });
  },
	// 上一题
	handleBefore(){
		let {
      questionList,
      questionNumber,
      answerOptionList,
      isCurrentStorage,
      maxLength,
    } = this.data
    let finalArr = []
    if(answerOptionList.length === maxLength){
      let finalArr1 = this.truncate(answerOptionList)
      finalArr = this.truncate(finalArr1)
    }else{
      finalArr = this.truncate(answerOptionList)
    }
    
		this.setData({
			answerOptionList: finalArr,
			currentOptionCode: '',
			currentQuestion: questionList[questionNumber - 1],
			questionNumber: questionNumber - 1,
    })

		if(questionNumber-1 === 0){
			if(isCurrentStorage === 1){
        this.setData({
          answerOptionList: [],
          isCurrentStorage: 0
        })
        app.removeQuestionStorage()
			}
		}
	},
	// 下一题
  handleNext() {
    let {
      questionList,
      questionNumber,
      answerOptionList,
			currentQuestion,
      maxLength,
    } = this.data
    let optionScore = ''
    console.log('handleNext----currentQuestion----',currentQuestion)
		// 单选
		currentQuestion?.optionList?.map((item) => {
			if (item.checked) {
        optionScore = item.fraction
			}
    })
    if (!optionScore) {
      wx.showToast({
        title: '请选择答案!',
        icon: 'none',
      })
      return
    }
    if(questionNumber+1 === maxLength && answerOptionList.length === maxLength){
      answerOptionList = this.truncate(answerOptionList) // answerOptionList.slice(0,answerOptionList.length-1)
    }
    answerOptionList.push({
      questionId: currentQuestion.id,
      executiveSkill: currentQuestion.executiveSkill,
      optionScore
    })
    this.setData({
      answerOptionList
    })
		if(questionNumber+1 === maxLength){
			return
    }
    questionList[questionNumber + 1]?.optionList.map((item) => {
			item.checked = false
		})

		this.setData({
			currentOptionCode: '',
			currentQuestion: questionList[questionNumber + 1],
			questionNumber: questionNumber + 1,
    })
  },
  // 提交
  handleSubmit: async function () {
    const {
      patientId,
      answerOptionList,
      isChild,
      crowd,
      currentQuestion,
      isCurrentStorage
    } = this.data

    let optionScore = ''

		// 单选
		currentQuestion.optionList.map((item) => {
			if (item.checked) {
        optionScore = item.fraction
			}
		})

    if (!optionScore) {
      wx.showToast({
        title: '请选择答案!',
        icon: 'none',
      })
      return
    }

    if(this.isLoading){
      return
    }
    let answerList = isChild === 1 ? this.up(answerOptionList) : answerOptionList
    
    this.isLoading = true

    let params = {
      childOrParent: isChild, // 孩子还是家长答题( 1:孩子 , 2:家长)
      patientId, // 孩子档案id
      questionList: answerList, // 答案列表
      schoolAge: crowd, // 学龄（1：入学前；2：1-3年纪；3：4-5年纪；4：6-8年纪；5：家长；）
    }
    console.log('params-----',params)

		let res = await request.post(api.childCalculation, params, { loading: false })
		if (res.httpStatus === 200) {
			wx.redirectTo({
        url: '/pages/activity/evaluationResult/index'
      })
      this.setData({
        answerOptionList: []
      })
      if(isCurrentStorage === 1){
        this.setData({
          isCurrentStorage: 0
        })
        app.removeQuestionStorage()
      }
      setTimeout(()=>{
        this.isLoading = false
      },1000)
		}else{
      this.isLoading = false
    }
  },
  // 弹窗点击“退出”
  handleCancle(){
    this.setData({
      warnShow: false
    })
    let { userId, patientId, answerOptionList, maxLength, isChild } = this.data

    setStorage("evaluationUserId",userId)
    setStorage("evaluationPatientId",patientId)
    let answerOptionArr = answerOptionList
    if( answerOptionArr.length === maxLength ){
      answerOptionArr = answerOptionArr.slice(0,answerOptionList.length-1)
    }
    setStorage("evaluationAnswerList",answerOptionArr)
    setStorage("evaluationIsChild",isChild)

    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  // 弹窗点击“继续评估”
  handleContinue(){
    this.setData({
      warnShow: false
    })
  },
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},
  handleBack(){
    let { answerOptionList} = this.data
		if(answerOptionList.length > 0){
      this.setData({
        warnShow: true
      })
		}else{
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
  },
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
    let { userId, patientId, answerOptionList, maxLength, isChild, isCurrentStorage } = this.data
		if(answerOptionList.length > 0){
      this.setData({
        warnShow: true
      })
			setStorage("evaluationUserId",userId)
			setStorage("evaluationPatientId",patientId)
			let answerOptionArr = answerOptionList
			if( answerOptionArr.length === maxLength ){
				answerOptionArr = answerOptionArr.slice(0,answerOptionList.length-1)
			}
			setStorage("evaluationAnswerList",answerOptionArr)
			setStorage("evaluationIsChild",isChild)
		}else{
      if(isCurrentStorage === 1){
        this.setData({
          answerOptionList: []
        })
        app.removeQuestionStorage()
      }
    }
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},
})
